package com.hngy.xpq.sqlitedemo;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;

import com.hngy.xpq.sqlitedemo.bean.Data;
import com.hngy.xpq.sqlitedemo.database.DataSql;

public class MainActivity extends AppCompatActivity {

    private EditText name, pass;
    private TextView showData;
    private Button insert, delete, update, select1;
    private DataSql dataSql;
    private Data data;  // 查询到的数据

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // 初始化
        init();
    }

    private void init() {
        // EditText
        name = findViewById(R.id.name);
        pass = findViewById(R.id.pass);
        showData = findViewById(R.id.showData);
        // Button
        insert = findViewById(R.id.insert);
        delete = findViewById(R.id.delete);
        update = findViewById(R.id.update);
        select1 = findViewById(R.id.select1);
        // 触发事件
        insert.setOnClickListener(new onclick());
        delete.setOnClickListener(new onclick());
        update.setOnClickListener(new onclick());
        select1.setOnClickListener(new onclick());
        // 初始化数据库
        dataSql = new DataSql(this);
    }

    class onclick implements Button.OnClickListener{
        @Override
        public void onClick(View v) {
            // 判断内容是否为空或者内容需要满足什么条件（这我就不写了）
            // 包装数据
            Data d = new Data();
            d.setName(name.getText().toString());
            d.setPass(pass.getText().toString());
            switch (v.getId()) {
                case R.id.insert:  // 增
                    result(dataSql.insert(d));
                    break;
                case R.id.delete:  // 删
                    if (data == null) {
                        showData.setText("请先查询!!");
                    } else {
                        result(dataSql.delete(data.getId()));
                    }
                    break;
                case R.id.update:  // 改
                    result(dataSql.update(d));
                    break;
                case R.id.select1: // 查
                    // 根据name查询
                    data = dataSql.select(d.getName());
                    if (data == null) {
                        showData.setText("不存在!!");
                    } else {
                        showData.setText(data.toString());
                    }
                    break;
                default:
                    break;
            }
        }
    }

    private void result(boolean i) {
        if (i) {
            Log.i("dataSql-result","处理成功!");
            showData.setText("处理成功!!");
        } else {
            Log.i("dataSql-result","不存在!");
            showData.setText("不存在!!");
        }
    }
}